//
//  MailConfirmOrderVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/6/12.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "MailConfirmOrderVC.h"
#import "MailConfirmOrderVC.h"
#import "MailConfirmOrderHeadView.h"
#import "MailConfirmOrderGoodsCell.h"
#import "MailConfirmOrderFooterView.h"
#import "MailConfirmOrderBottomView.h"
#import "UserShippingAddressVC.h"
#import "OrderPayVC.h"
#import "UserOrderChildGroupView.h"

@interface MailConfirmOrderVC ()

@property (nonatomic,strong) MailConfirmOrderHeadView *headView;

@property (strong, nonatomic)MailConfirmOrderBottomView *bottomView;

@property (weak, nonatomic)SelectorShenFenView *htView;
@end

@implementation MailConfirmOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
        
    
    self.defaultStartPage = 1;
    self.title = @"确认订单";
//    [self creatTableViewWithCellIdentity:@"MailConfirmOrderGoodsCell"];
    [self creatTableViewStyle:UITableViewStyleGrouped cellIdentity:@"MailConfirmOrderGoodsCell"];
    self.view.backgroundColor = kRGBColor(246, 246, 246);
    self.tableView.backgroundColor = kRGBColor(246, 246, 246);
    self.tableView.rowHeight = 110;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, NavBarHeight, kScreenW, kScreenH-NavBarHeight -NeedStatusViewHeight-49);
    
    ShoppingCartModel *model = self.modelArray[0];
    ShoppingCartGoodsMode *goodsModel = model.shopping_car_list[0];
    if (goodsModel.num == 0) {
        goodsModel.num = 1;
    }
    if (goodsModel.sku_type != 3 &&goodsModel.sku_type != 9) {
        self.tableView.tableHeaderView = self.headView;
    }
    
    [self.view addSubview:self.bottomView];
    [self queryDefAddress];
        
}

- (MailConfirmOrderHeadView *)headView {
 
    if (!_headView) {
       
        _headView = [[NSBundle mainBundle] loadNibNamed:@"MailConfirmOrderHeadView" owner:self options:nil].lastObject;
        _headView.frame = CGRectMake(0, 0, kScreenW, 70);
        for (ShoppingCartModel *model in self.modelArray) {
               for (ShoppingCartGoodsMode *goodModel in model.shopping_car_list) {
//                   if (goodModel.is_ht == 2) {
//                       _headView.frame = CGRectMake(0, 0, kScreenW, 130);
//                       _headView.shenfenHeight.constant = 60;
//                       [_headView queryUserIdcardList];
//                       self.is_ht = 2;
//                   }
               }
           }

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectorAddressModel)];
        [_headView.addressBgView addGestureRecognizer:tap];
        
        UITapGestureRecognizer *shenfenTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectorShenFenModel)];
        [_headView.shenfenBgBiew addGestureRecognizer:shenfenTap];
        
    }
    
    return _headView;
}

#pragma mark - 选择地址
- (void)selectorAddressModel {
    
    UserShippingAddressVC *vc = [[UserShippingAddressVC alloc]init];
    vc.selectorAddressModel = ^(UserShipingAddressModel *model) {
        self.addressModel = model;
        self.headView.model = self.addressModel;

    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 选择身份信息
- (void)selectorShenFenModel {
    
    self.htView = [SelectorShenFenView showView];
    self.htView.htModel = self.headView.htModel;

    
}





- (MailConfirmOrderBottomView *)bottomView {
    
    if (!_bottomView) {
        
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"MailConfirmOrderBottomView" owner:self options:nil].lastObject;
        _bottomView.frame = CGRectMake(0, KSCREEN_HEIGHT -49 -NeedStatusViewHeight, kScreenW, 49);
        [_bottomView.nextBtn addTarget:self action:@selector(saveOrder) forControlEvents:UIControlEventTouchUpInside];
        [self refreshPrcieAndNum];
    }
    
    return _bottomView;
}

#pragma mark - 刷新价格和数量
- (void)refreshPrcieAndNum {
    
    float price = 0;
    float Courier = 0;
    int num = 0;
    for (ShoppingCartModel *model in self.modelArray) {
        for (ShoppingCartGoodsMode *goodModel in model.shopping_car_list) {
            if (goodModel.is_yk == 2) {
                price += goodModel.num *goodModel.yk_price;
            }else if (goodModel.sku_type == 2|| goodModel.sku_type == 9) {
                price += goodModel.num *goodModel.buy_price;
            }else if (self.order_type == 4) {
                price += goodModel.num *goodModel.pt_price;
            }else {
                price += goodModel.num *goodModel.vip_price;
            }
            Courier += goodModel.freight_price;
            num += goodModel.num;
        }

    }
    //把运费加上
    price += Courier;
    self.bottomView.numLabel.text = [NSString stringWithFormat:@"共%d件",num];
    self.bottomView.priceLabel.text = [CommonTTool getPrice:price];
    
   
    
    
}


    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    MailConfirmOrderGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailConfirmOrderGoodsCell"];
    ShoppingCartModel *model = self.modelArray[indexPath.section];
    cell.order_type = self.order_type;
    cell.model = model.shopping_car_list[indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    ShoppingCartModel *model = self.modelArray[section];
    
    return model.shopping_car_list.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.modelArray.count;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UserOrderChildGroupView *view = [[NSBundle mainBundle] loadNibNamed:@"UserOrderChildGroupView" owner:self options:nil].lastObject;
    ShoppingCartModel *model = self.modelArray[section];
    view.nameLabel.text = model.business_name;
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    MailConfirmOrderFooterView *footerView = [[NSBundle mainBundle] loadNibNamed:@"MailConfirmOrderFooterView" owner:self options:nil].lastObject;
    footerView.frame = CGRectMake(0, 0, kScreenW, 135);
    
    float price = 0;
    float Courier = 0;
    int num = 0;
    ShoppingCartModel *model = self.modelArray[section];
   for (ShoppingCartGoodsMode *goodModel in model.shopping_car_list) {
       if (goodModel.is_yk == 2) {
           price += goodModel.num *goodModel.yk_price;
       }else if (goodModel.sku_type == 2 || goodModel.sku_type == 9) {
           price += goodModel.num *goodModel.buy_price;
       }else if (self.order_type == 4) {
           price += goodModel.num *goodModel.pt_price;
       }else {
           price += goodModel.num *goodModel.vip_price;
       }
       Courier += goodModel.freight_price;
       num += goodModel.num;
   }
    
    //小计加上运费
    price += Courier;
    footerView.numLabel.text = [NSString stringWithFormat:@"共%d件",num];
    footerView.priceLabel.text = [CommonTTool getPrice:price];
    if (Courier == 0) {
        footerView.courierLabel.text = @"包邮";
    }else {
        footerView.courierLabel.text = [NSString stringWithFormat:@"快递￥%@",[CommonTTool getPrice:Courier]];

    }
    footerView.model = model;
    ShoppingCartGoodsMode *goodModel = model.shopping_car_list[0];
    if (goodModel.sku_type == 3 || goodModel.sku_type == 9) {
        footerView.yundeiHeight.constant = 0;
    }
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    ShoppingCartModel *model = self.modelArray[section];
    ShoppingCartGoodsMode *goodModel = model.shopping_car_list[0];
    if (goodModel.sku_type == 3 || goodModel.sku_type == 9) {
        return 100;
    }
    return 135;
}


- (void)queryDefAddress {
    
    [NetRequestTool postUrl:@"address/queryDefAddress" parameters:@{} success:^(id responseObject) {
        
        self.addressModel = [UserShipingAddressModel mj_objectWithKeyValues:responseObject[@"object"]];
        
        if ([CommonTTool isStrNull:self.addressModel.address_id]) {
            self.headView.nameLabel.hidden = YES;
            self.headView.phoneLabel.hidden = YES;
            self.headView.addressLabel.hidden = YES;
            self.headView.nullAddressLabel.hidden = NO;
        }else {
            self.headView.model = self.addressModel;
        }
        
    } failure:^(NSInteger statusCode) {
        self.headView.nameLabel.hidden = YES;
        self.headView.phoneLabel.hidden = YES;
        self.headView.addressLabel.hidden = YES;
        self.headView.nullAddressLabel.hidden = NO;
    } finish:^{
        
    }];
    
}

- (void)startPt {
    

    
    if ([CommonTTool isStrNull:self.addressModel.address_id]) {
        SVP(@"请选择收货地址");
        return;
    }
    ShoppingCartModel *model = self.modelArray[0];
    ShoppingCartGoodsMode *goodsModel = model.shopping_car_list[0];
    NSMutableDictionary*para = [NSMutableDictionary dictionary];
    [para setObject:goodsModel.sku_id forKey:@"sku_id"];
    [para setObject:@(goodsModel.num) forKey:@"num"];
    if (![CommonTTool isStrNull:model.remarks]) {
        [para setObject:model.remarks forKey:@"remark"];
    }
    [para setObject:self.addressModel.address_id forKey:@"address_id"];
    if (self.isAddPt) {
        [para setObject:@(2) forKey:@"is_pt_type"];
        [para setObject:self.tg_group_id forKey:@"tg_group_id"];

    }else {
        [para setObject:@(1) forKey:@"is_pt_type"];

    }

    [NetRequestTool postUrl:@"skuOrder/savePtOrder" parameters:para success:^(id responseObject) {
        NSString *order = responseObject[@"object"];
        OrderPayVC *vc = [[OrderPayVC alloc]init];
        vc.type = self.order_type;
        vc.parent_order_code = order;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
}

- (void)xuniSave {
    
    ShoppingCartModel *model = self.modelArray[0];
    ShoppingCartGoodsMode *goodsModel = model.shopping_car_list[0];
    NSMutableDictionary*para = [NSMutableDictionary dictionary];
    [para setObject:goodsModel.sku_id forKey:@"sku_id"];
    [para setObject:@(goodsModel.num) forKey:@"num"];
    if (![CommonTTool isStrNull:model.remarks]) {
        [para setObject:model.remarks forKey:@"remark"];
    }
    if (self.is_ht == 2) {
        if ([CommonTTool isStrNull:self.headView.htModel.user_idcard_id]) {
            SVP(@"请输入您的实名信息");
            return;
        }
        [para setObject:@"2" forKey:@"is_ht"];
        [para setObject:self.headView.htModel.user_idcard_id forKey:@"user_idcard_id"];
    }

    SVPShowInternetWaiting;
    [NetRequestTool postUrl:@"skuOrder/saveXnOrder" parameters:para success:^(id responseObject) {
           NSString *order = responseObject[@"object"];
           OrderPayVC *vc = [[OrderPayVC alloc]init];
           vc.type = self.order_type;
           vc.parent_order_code = order;
            vc.is_ht = self.is_ht;
           [self.navigationController pushViewController:vc animated:YES];
           
       } failure:^(NSInteger statusCode) {
           
       } finish:^{
           
       }];
    
       
}

#pragma mark - 保存订单
- (void)saveOrder {
    
    
    if (self.order_type == 4) {
        [self startPt];
        return;
    }
    if (self.order_type == 3 || self.order_type == 9) {
        [self xuniSave];
        return;
    }
    

    NSMutableDictionary*para = [NSMutableDictionary dictionary];
    NSMutableArray *goods_order_detail_list = [NSMutableArray array];
    NSMutableDictionary *remarks = [NSMutableDictionary dictionary];
    
    if ([CommonTTool isStrNull:self.addressModel.address_id]) {
        SVP(@"请选择收货地址");
        return;
    }
     
    for (ShoppingCartModel *superModel in self.modelArray) {
        if (![CommonTTool isStrNull:superModel.remarks]) {
            
            [remarks setObject:superModel.remarks forKey:superModel.business_id];
        }
        for (ShoppingCartGoodsMode *model in superModel.shopping_car_list) {
            
            NSDictionary *dict = @{@"sku_id":model.sku_id,
                                          @"num":@(model.num),
                                          @"business_id":model.business_id,
                                          @"sku_type":@(model.sku_type)
                                          
            };
            [goods_order_detail_list addObject:dict];
        }
       
        
    }
    NSData *dataFriends = [NSJSONSerialization dataWithJSONObject:goods_order_detail_list options:NSJSONWritingPrettyPrinted error:nil];

    NSString *jsonString = [[NSString alloc] initWithData:dataFriends encoding:NSUTF8StringEncoding];
    if (remarks.count > 0) {
        NSData *dataFriends = [NSJSONSerialization dataWithJSONObject:remarks options:NSJSONWritingPrettyPrinted error:nil];

        NSString *jsonString = [[NSString alloc] initWithData:dataFriends encoding:NSUTF8StringEncoding];
        [para setObject:jsonString forKey:@"remarks_map"];
    }
//    [para setObject:@"JSON" forKey:@"JSON"];

    [para setObject:self.addressModel.address_id forKey:@"address_id"];
    [para setObject:jsonString forKey:@"goods_order_detail_list"];

    if (self.shopping_car_ids != nil) {
        [para setObject:self.shopping_car_ids forKey:@"shopping_car_ids"];
    }
    
    if (self.is_ht == 2) {
        if ([CommonTTool isStrNull:self.headView.htModel.user_idcard_id]) {
            SVP(@"请输入您的实名信息");
            return;
        }
        [para setObject:@"2" forKey:@"is_ht"];
        [para setObject:self.headView.htModel.user_idcard_id forKey:@"user_idcard_id"];
    }

    
    
    [NetRequestTool postUrl:@"skuOrder/saveOrder" parameters:para success:^(id responseObject) {
        
        NSString *order = responseObject[@"object"];
        OrderPayVC *vc = [[OrderPayVC alloc]init];
        vc.type = self.order_type;
        vc.parent_order_code = order;
        vc.is_ht = self.is_ht;
        [self.navigationController pushViewController:vc animated:YES];
        
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
    
}

@end
